<template>
  <view>
    <view class="form-view">
      <view class="form-card" v-if="false">
        <view class="form-row">
          <view class="label">标题</view>
          <view class="placeholder-class">请选择</view>
          <uni-icons type="right" color="rgba(35,35,35,0.4)" />
        </view>
        <view class="div-line-type-1" />
        <view class="form-row">
          <view class="label">标题</view>
          <view class="placeholder-class">请选择</view>
          <uni-icons type="right" color="rgba(35,35,35,0.4)" />
        </view>
      </view>

      <view class="form-desc-form">
        <textarea
          v-model="form.servicesSummarize"
          placeholder-class="placeholder-class"
          placeholder="请填写您对本次服务的总结，以便其他医护人员全面了解该患者的情况"></textarea>
        <view class="div-line" />
        <view class="label">附图（选填）</view>
        <uni-grid :column="3" :highlight="false" :showBorder="false">
          <uni-grid-item v-for="item in servicesSummarizeImageList">
            <view class="image-grid-item" @click="previewImage(item)">
              <image :src="item"></image>
            </view>
          </uni-grid-item>
          <uni-grid-item v-if="servicesSummarizeImageList.length < 9">
            <view
              class="image-grid-item"
              @click="uploadImageForServicesSummarize">
              <view class="grid-item-add">
                <uni-icons type="plusempty" color="#232323" />
                <view>上传图片</view>
              </view>
            </view>
          </uni-grid-item>
        </uni-grid>
      </view>

      <view class="switch-tab-view" v-if="false">
        <view class="label">下次预约服务时间</view>
        <view class="tab-view">
          <view
            @click="tabClick(item, index)"
            :class="current === index ? 'tab-item-selected' : ''"
            v-for="(item, index) in tabs"
            class="tab-item">
            {{ item }}
          </view>
        </view>
      </view>

      <view class="form-card last-view">
        <view class="form-row">
          <view class="label">废弃物名称</view>
          <view class="value">
            <picker
              :range="wasteNameList"
              :value="wasteNameIndex"
              @change="onWasteNameListChange">
              <view style="display: flex">
                <view v-if="form.wasteName" class="hospital-input">
                  {{ form.wasteName }}
                </view>
                <view v-else class="placeholder-class">请选择</view>
                <uni-icons type="right" color="#BABDC4" />
              </view>
            </picker>
          </view>
        </view>
        <view class="div-line-type-1" />
        <view class="form-row">
          <view class="label">投放地点</view>
          <input
            v-model="form.placementLocation"
            placeholder="请输入"
            placeholder-class="placeholder-class" />
        </view>

        <view class="form-desc-form">
          <view class="label requires">医疗废弃物品投放照片（必填）</view>
          <uni-grid :column="3" :highlight="false" :showBorder="false">
            <uni-grid-item v-for="item in wasteImageList">
              <view class="image-grid-item">
                <image :src="item"></image>
              </view>
            </uni-grid-item>
            <uni-grid-item v-if="wasteImageList.length < 9">
              <view class="image-grid-item" @click="uploadImageForWaste">
                <view class="grid-item-add">
                  <uni-icons type="plusempty" color="#232323" />
                  <view>上传图片</view>
                </view>
              </view>
            </uni-grid-item>
          </uni-grid>
        </view>
      </view>

      <view class="bottom-fixed-view">
        <view class="submit-btn" @click="submit">确认完成</view>
      </view>

      <view class="watermark-canvas">
        <canvas
          v-if="showCanvas"
          id="watermark-canvas"
          :style="{ width: canvasWidth, height: canvasHeight }"
          canvas-id="watermark-canvas" />
      </view>
    </view>
  </view>
</template>

<script>
import * as orderInfo from "../../common/api/orderInfo.js";
import * as upload from "../../common/upload.js";
export default {
  data() {
    return {
      uid: "",
      tabs: ["一周内", "半个月内", "一个月内", "暂不预约"],
      current: 0,
      canvasWidth: "",
      canvasHeight: "",
      showCanvas: true,
      servicesSummarizeImageList: [],
      wasteImageList: [],
      form: {
        servicesSummarize: "",
        wasteName: "",
        placementLocation: "",
      },
      wasteNameList: ["医疗垃圾", "生活垃圾"],
      wasteNameIndex: 0,
    };
  },
  onLoad(opt) {
    if (opt.uid) {
      this.uid = opt.uid;
    }
  },
  methods: {
    tabClick(item, index) {
      this.current = index;
    },
    previewImage(url) {
      uni.previewImage({
        urls: [url],
      });
    },
    getAddress(longitude, latitude) {
      return new Promise((resolve, reject) => {
        const key = "3cba451d85dfb3a05aebd8d3a70ed2c1"; //高德地图key
        uni.request({
          url: `https://restapi.amap.com/v3/geocode/regeo?output=json&location=${longitude},${latitude}&key=${key}&radius=1000&extensions=all`,
          data: {},
          header: {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
          },
          success(res) {
            console.log("高德地图API接口返回信息", res);
            console.log(res.data.regeocode.formatted_address);
            resolve(res.data.regeocode.formatted_address);
          },
          fail() {
            reject();
          },
        });
      });
    },
    getLocation() {
      return new Promise((resolve, reject) => {
        uni.getLocation({
          type: "wgs84",
          geocode: true,
          success(res) {
            console.log(JSON.stringify(res));
            console.log("当前位置的经度：" + res.longitude);
            console.log("当前位置的纬度：" + res.latitude);
            resolve(res);
          },
          fail() {
            reject();
          },
        });
      });
    },
    async addWatermark(tempFilePath) {
      function sleep(millisecond) {
        return new Promise((resolve) => {
          setTimeout(resolve, millisecond);
        });
      }
      return new Promise((resolve, reject) => {
        uni.getImageInfo({
          src: tempFilePath,
          success: async (res) => {
            //重新渲染canvas
            this.showCanvas = false;
            this.$nextTick(() => {
              this.showCanvas = true;
            });
            // 设置画布高度和宽度
            this.canvasWidth = `${res.width}px`;
            this.canvasHeight = `${res.height}px`;
            await sleep(200); // 某些平台 canvas 渲染慢，需要等待

            const ctx = uni.createCanvasContext("watermark-canvas", this);
            ctx.clearRect(0, 0, res.width, res.height);
            ctx.beginPath();
            ctx.drawImage(tempFilePath, 0, 0, res.width, res.height);

            // 水印 字体大小，颜色，内容，位置
            ctx.beginPath();
            ctx.setFontSize(24);
            ctx.setFillStyle("rgba(250,0,0,0.8)");
            //拍照时间、星期几，经纬度，地区
            const date = new Date();
            const dateText = date.format("yyyy-MM-dd hh:mm:ss");
            const weekArr = [
              "星期日",
              "星期一",
              "星期二",
              "星期三",
              "星期四",
              "星期五",
              "星期六",
            ];
            const week = weekArr[date.getDay()];
            const location = await this.getLocation();
            const longitude = location.longitude || ""; //经度
            const latitude = location.latitude || ""; //经度
            const address = await this.getAddress(longitude, latitude);
            const left = 30;
            const bottom = 30;
            ctx.fillText(
              `拍照时间 ${dateText} ${week}`,
              left,
              res.height - bottom * 4
            );
            ctx.fillText(`经度 ${longitude}`, left, res.height - bottom * 3);
            ctx.fillText(`纬度 ${latitude}`, left, res.height - bottom * 2);
            ctx.fillText(`地区 ${address}`, left, res.height - bottom * 1);
            // 开始绘制 (canvas -> 临时文件路径)
            ctx.draw(false, async () => {
              await sleep(500); // 某些平台 canvas 渲染慢，需要等待
              uni.canvasToTempFilePath(
                {
                  canvasId: "watermark-canvas",
                  destWidth: res.width,
                  destHeight: res.height,
                  fileType: "jpg",
                  quality: 0.8,
                  success: (fileRes) => {
                    resolve(fileRes.tempFilePath);
                  },
                  fail: (err) => {
                    console.log("[Error draw]", err);
                    uni.showToast({ title: err.errMsg, icon: "none" });
                    reject();
                  },
                },
                this
              );
            });
          },
          fail: (err) => {
            console.log("[Error getImageInfo]", err);
            uni.showToast({ title: err.errMsg, icon: "none" });
            reject();
          },
        });
      });
    },
    uploadImg() {
      uni.chooseImage({
        success: async (res) => {
          console.log(res.tempFilePaths);
          const img = await this.addWatermark(res.tempFilePaths[0]);
          this.list.push(img);
        },
      });
    },
    endService() {
      uni.showModal({
        title: "提示",
        content: "结束服务？",
        success: (res) => {
          if (res.confirm) {
            console.log("用户点击确定");
            const param = {
              uid: this.uid,
              status: "已完成",
            };
            orderInfo
              .update(param)
              .then((result) => {})
              .catch((error) => {
                console.log(error);
              });
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
    },
    uploadImageForServicesSummarize() {
      upload
        .saveFileMoreParam({
          mainItemUid: this.uid,
          fileType: "服务总结",
        })
        .then((result) => {
          console.log(result);
          this.servicesSummarizeImageList.push(result.data.url);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    uploadImageForWaste() {
      upload
        .saveFileMoreParam({
          mainItemUid: this.uid,
          fileType: "废弃物品",
        })
        .then((result) => {
          console.log(result);
          this.wasteImageList.push(result.data.url);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    checkForm() {
      const showMsg = (msg = "") => {
        if (msg) {
          uni.showToast({
            title: msg,
            icon: "none",
          });
        }
      };
      if (!this.wasteImageList || this.wasteImageList.length <= 0) {
        showMsg("废弃物品图片不能为空");
        return false;
      }
      return true;
    },
    submit() {
      if (!this.checkForm()) {
        return;
      }
      uni.showModal({
        title: "提示",
        content: "确认提交？",
        success: (res) => {
          if (res.confirm) {
            console.log("用户点击确定");
            const param = {
              uid: this.uid,
              status: "已完成",
              ...this.form,
            };
            orderInfo
              .update(param)
              .then((result) => {
                uni.navigateBack();
              })
              .catch((error) => {
                console.log(error);
              });
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
    },
    onWasteNameListChange(e) {
      this.form.wasteName = this.wasteNameList[e.detail.value];
      console.log(JSON.stringify(this.form));
    },
  },
};
</script>

<style lang="scss" scoped>
.form-view {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.form-card {
  background: white;
  .form-row {
    display: flex;
    background: white;
    padding: 0 30rpx;
    height: 120rpx;
    align-items: center;
    .label {
      flex: 1;
      color: #232323;
      font-size: 32rpx;
      font-weight: bold;
    }

    input {
      text-align: end;
    }
    .placeholder-class {
      color: rgba(35, 35, 35, 0.4);
      font-size: 32rpx;
    }
    .uni-icons {
      margin-left: 16rpx;
    }
  }
  .div-line-type-1 {
    width: calc(100% - 30rpx);
    background: #f8f8f8;
    height: 2rpx;
    margin-left: 30rpx;
  }
}

.form-desc-form {
  background: white;
  width: 100%;
  display: flex;
  flex-direction: column;
  padding: 30rpx;
  box-sizing: border-box;
  margin-top: 20rpx;
  textarea {
    width: 100%;
  }
  .placeholder-class {
    color: rgba(35, 35, 35, 0.4);
    font-size: 32rpx;
  }
  .div-line {
    width: 100%;
    height: 2rpx;
    background: #f8f8f8;
  }
  .label {
    color: rgba(35, 35, 35, 0.5);
    font-size: 26rpx;
    margin-top: 20rpx;
  }
}

.image-grid-item {
  width: 100%;
  height: 100%;
  padding: 10rpx;
  box-sizing: border-box;
  image {
    width: 100%;
    height: 100%;
    border-radius: 12rpx;
  }
  .grid-item-add {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: #fdfdfd;
    border-radius: 12rpx;
    border: dashed 2rpx #e1e1e1;
    color: rgba(35, 35, 35, 0.7);
    font-size: 24rpx;
  }
}

.switch-tab-view {
  width: 100%;
  padding: 30rpx;
  background: white;
  box-sizing: border-box;
  margin-top: 20rpx;
  .label {
    color: #232323;
    font-size: 32rpx;
  }
  .tab-view {
    margin-top: 30rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .tab-item {
      background: #f6f6f6;
      min-width: 160rpx;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 40rpx;
      color: rgba(35, 35, 35, 0.8);
      font-size: 26rpx;
    }
    .tab-item-selected {
      background: #2eb0d9;
      color: white;
    }
  }
}

.last-view {
  margin-top: 20rpx;
  margin-bottom: 130rpx;
}

.bottom-fixed-view {
  width: 100%;
  height: 108rpx;
  position: fixed;
  background: white;
  padding: 14rpx 30rpx;
  box-sizing: border-box;
  bottom: 0;
  .submit-btn {
    width: 100%;
    height: 80rpx;
    background: #2eb0d9;
    border-radius: 40rpx;
    color: white;
    font-size: 30rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.watermark-canvas {
  position: absolute;
  top: 5px;
  left: 5px;
  width: 1px;
  height: 1px;
  overflow: hidden;
}

.requires::after {
  content: "*";
  color: #e74242;
}
</style>
